const express = require("express");
const webpackDevMiddleware= require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const app = express();
const webpack = require("webpack");
const devConfig = require("./webpack.dev.config");
const compiler = webpack(devConfig);
const path = require("path");
const electronUtils = require("./electron-utils");

const devMiddleware = webpackDevMiddleware(compiler, {
    publicPath: devConfig.output.publicPath,
    quiet: false
});

const hotMiddleware = webpackHotMiddleware(compiler, {
    log: false,
    heartbeat: 2000
});

app.use(hotMiddleware);
app.use(devMiddleware);

// 设置静态文件地址
app.use(express.static(path.resolve(__dirname, "../dist")));

// 设置端口号
let port = 8099;
process.env.PORT = port;
const portfinder = require("portfinder");
portfinder.basePort = port;

let _reject = null;
let _resolve = null;
let server = null;
let _promise = new Promise((resolve, reject) => {
    _resolve = resolve;
    _reject = reject;
});


// 等待编译完成
devMiddleware.waitUntilValid( function () {
    portfinder.getPort((error, port) => {
        if(error){
            _reject(error)
        }
        process.env.PORT = port;
        server = app.listen(port);
        process.env.NODE_ENV = "development"; // 设置为开发环境
        electronUtils.runElectron();
        _resolve();
    });
});

module.exports = {
    ready:_promise,
    close: () => {
        server.close();
        process.exit(0);
    }
};
